var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('receiptCtrl', function($scope, $http) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$('input[name = "backDt"], input[name = "receiptDt"], input[name = "mustDt"]').datetimepicker({
			format : "yyyy-mm-dd hh:ii",
			minView : "month",
		    todayBtn : "linked",
		    language : "zh-CN",
		    forceParse : false,
		    autoclose : true,
		    todayHighlight : true
		});
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
		httpPost($http, {"url":ctx + "/client/findListByFirst", "ifBlock" : true}, function(data){
			$scope.clientList = data.dt;
		}, function(){
			toastError("初始化客户列表失败。");
		});
		
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "legsId",
			displayName : "legsId", visible : false
		},
		{
			field : "clientName",
			displayName : "客户",
			width : 160
		},
		{
			field : "cd",
			displayName : "订单编号",
			width : 160
		},
		{
			field : "legsCd",
			displayName : "分段订单号",
			width : 160
		},
		{
			field : "cityName",
			displayName : "城市",
			width : 120
		},
		{
			field : "vocationName",
			displayName : "业务类型",
			width : 160
		},
		{
			field : "statusName",
			displayName : "回单状态",
			width : 160
		},
		{
			field : "quantity",
			displayName : "数量",
			width : 160
		},
		{
			field : "signMan",
			displayName : "签收人",
			width : 160
		},
		{
			field : "receiptDt",
			displayName : "回单时间",
			width : 160,
			cellFilter : "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "account",
			displayName : "配送异常情况", 
			width : 300
		},
		{
			field : "rtime",
			displayName : "退货时间",
			width : 160,
			cellFilter : "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "carNo",
			displayName : "车牌号",
			width : 160
		},
		{
			field : "driverName",
			displayName : "司机",
			width : 160
		},
		{
			field : "freceiverName",
			displayName : "发货方",
			width : 160
		},
		{
			field : "treceiverName",
			displayName : "收货方",
			width : 160
		},
		{
			field : "arriveDt",
			displayName : "运抵时间",
			width : 160,
			cellFilter : "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "mustDt",
			displayName : "应回单时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "reason",
			displayName : "延时原因",
			width : 255
		},
		{
			field : "backDt",
			displayName : "返还客户时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "shipmentCd",
			displayName : "调度单号",
			width : 160
		}
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n: 'zh-cn', rowHeight : 21, footerRowHeight : 35,
		showFooter : true
	};

	//查询
	$scope.query = function() {
		closeModal($("#queryFormModal"));
		hideShadow();
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/receipt/findListBy', "data" : requestBody, "ifBlock" : true}, function(data){
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
				if(data.dt.length === 0){
					toastWarning("没有找到符合查询条件的记录。");
				};
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//trigger query when currentPage not change
	$scope.onQuery = function(){
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};
	
	//更新
	$scope.refresh=function(){
		hideShadow();
		$scope.onQuery();	
	};

	//导出
	$scope.onOpenExportFormModal = function(){	
		var params;
		if($scope.queryForm == undefined){
			params="";
		}else{
			params = $scope.queryForm;
		}
		var str = jQuery.param(params);
		window.open(ctx  + '/receipt/export?' + str);
	};
	
	
	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//打开查询框
	var list = [];
	$scope.onOpenQueryFormModal = function() {
		hideShadow();
		if(list.length === 0){
			httpPost($http, {"url":ctx + "/dict/getDictByCd", "params":{"cd" : "shipment"}, "ifBlock" : true}, function(data){
				$.each(data.dt, function(idx, obj){
					if(obj.descr == 'arrive'){
						list.push(obj);
					}
				});
				httpPost($http, {"url":ctx + "/dict/getDictByCd", "params":{"cd" : "receiptStatus"}, "ifBlock" : true}, function(data){
					$.each(data.dt, function(idx, obj){
						list.push(obj);
					});
				});
			});
			$scope.statusList = list;
		}
		openModal($("#queryFormModal"));
	};
	
	//标记不合格回单
	$scope.sign = function(){
		hideShadow();
		var selectedRowsId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
		});
		dialogConfirm("是否标记为不合格回单？", function(){
			httpPost($http, {"url":ctx + '/receipt/updStByIds', "params":{"ids" : selectedRowsId, "status" : 'FAULT'}, "ifBlock" : true}, function(data){
				$scope.onQuery();
			});
		});
	};
	
	//整单签收
	$scope.onOpenRCPModal = function() {
		if($scope.selectedRows.length < 1) { toastWarning("请至少选择一笔记录进行确认。"); return; }
		$scope.editFormRcp = {};
		var date = (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate()) + " " + ((date.getHours()> 9) ? date.getHours() : "0" + date.getHours()) + ":" + ((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormRcp.receiptDt = now;
		hideShadow();
		openModal($("#rcpModal"));
	};
	
	$scope.receipt=function(){
		closeModal($("#rcpModal"));
		var selectedRowsId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
		});
		httpPost($http, {"url":ctx + '/receipt/updByIds', "params":{"ids" : selectedRowsId,"receiptDt" : $scope.editFormRcp.receiptDt}, "ifBlock" : true}, function(data){
			$scope.onQuery();
		});
	};
	
	//返还客户
	$scope.changeStModal = function(){
		$scope.editFormCt = {};
		if($scope.selectedRows.length < 1) { toastWarning("请至少选择一笔记录进行操作。"); return; }
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate()) + " " + ((date.getHours()> 9) ? date.getHours() : "0" + date.getHours()) + ":" + ((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormCt.backDt = now;
		hideShadow();
		openModal($("#changStModal"));
	};
	
	$scope.changeSt = function(){
		closeModal($("#changStModal"));
		var selectedRowsId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
		});
		httpPost($http, {"url":ctx + '/receipt/chageStByIds',"params":{"ids" : selectedRowsId, "backDt" : $scope.editFormCt.backDt}, "ifBlock" : true}, function(data){
			$scope.onQuery();
		});
	};
	
	//修改应回单时间
	$scope.changMsModal = function(){
		$scope.editForm = {};
		if($scope.selectedRows.length < 1) { toastWarning("请至少选择一笔记录进行操作。"); return; }
		var date = (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate()) + " " + ((date.getHours()> 9) ? date.getHours() : "0" + date.getHours()) + ":" + ((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editForm.mustDt = now;
		hideShadow();
		openModal($("#changMsModal"));
	};
	
	$scope.changeMustDt = function(){
		closeModal($("#changMsModal"));
		var selectedRowsId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
		});
		httpPost($http, {"url":ctx + '/receipt/changeMustDt',"params":{"ids" : selectedRowsId, "mustDt" : $scope.editForm.mustDt}, "ifBlock" : true}, function(data){
			$scope.onQuery();
		});
	};
	
	//撤销回单
	$scope.cancelRcp = function(){
		hideShadow();
		var selectedRowsId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
		});
		dialogConfirm("是否确认撤销选择的" + $scope.selectedRows.length + "笔回单？", function(){
			httpPost($http, {"url":ctx + '/receipt/cancelRcp', "params":{"ids" : selectedRowsId}, "ifBlock" : true}, function(data){
				$scope.onQuery();
			});
		});
	};
	
	//延时单确认
	$scope.onOpenNntConfirmModal = function(){
		hideShadow();
		var id = $scope.selectedRows[0]['id']; 
		httpGet($http, {"url":ctx + '/receipt/id/' + id, "ifBlock" : true}, function(data){
			$scope.editFormNnt = data.dt;
		}, function(errMsg){
			toastWarning("查询此笔记录失败。");
		});
		openModal($("#nntModal"));
	};
	
	$scope.nntConfirm = function(){
		closeModal($("#nntModal"));
		httpPost($http, {"url":ctx + '/receipt/updReasonById', "params":{"id" : $scope.editFormNnt.id, "reason" : $scope.editFormNnt.reason}, "ifBlock" : true}, function(data){
			$scope.onQuery();
		});
	};
	
	//右键菜单功能
	$('#mainDataBlock').contextMenu('menu', {
	      //菜单项样式
	      itemStyle: {
	        fontFamily : 'verdana',
	        backgroundColor : '#F0F0F0',
	        border: 'none',
	        padding: '4px'
	      },
	      //菜单项鼠标放在上面样式
	      itemHoverStyle: {
	        border: '1px solid #fff'
	      },
	      onShowMenu: function(e, menu) {
	    	  var sts = [];
				for(var i = 0; i < $scope.selectedRows.length; i++){
					var st = $scope.selectedRows[i]['status'];
					if(jQuery.inArray( st, sts ) < 0){
						sts.push(st);
					}
				}
				if($scope.selectedRows.length === 0){
					$('#rcp,#return, #nnt,#sign,#cancel,#must', menu).remove();
				}else if($scope.selectedRows.length === 1){
					if(sts.length == 1){
						if(sts[0] == 'arrive'){
							$('#return,#cancel', menu).remove();
						}else if(sts[0] == 'FAULT'){
							$('#return,#sign,#cancel', menu).remove();
						}else if(sts[0] == 'QUALIFIED'){
							$('#rcp,#nnt,#sign,#must', menu).remove();
						}else{
							$('#rcp,#nnt,#sign,#return,#must', menu).remove();
						}
					}
				}else{
					if(sts.length == 1){
						if(sts[0] == 'arrive'){
							$('#return,#cancel', menu).remove();
						}else if(sts[0] == 'FAULT'){
							$('#return,#sign,#cancel', menu).remove();
						}else if(sts[0] == 'QUALIFIED'){
							$('#rcp,#nnt,#sign,#must', menu).remove();
						}else{
							$('#rcp,#nnt,#sign,#return,#must', menu).remove();
						}
					}else{
						$('#rcp,#nnt,#sign,#return,#cancel,#must', menu).remove();
					}
				}
	        return menu;
	      }
		});
});